package br.com.Login.dao;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import br.com.Login.bean.Autorizacao;
import br.com.Login.bean.User;
import br.com.ProjetoTCC_JSF.metodos.ConverterSenha;
import br.com.ProjetoTCC_JSF.modelo.dao.CreateEntityManagerFactory;
import br.com.ProjetoTCC_JSF.modelo.dao.DaoResource;
import br.com.ProjetoTCC_JSF.modelo.dao.Persisted;

public class UserDao implements Persisted{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private EntityManagerFactory factory;
	private EntityManager manager;
	private DaoResource daoResource;

	@Override
	public EntityManagerFactory createEntityManagerFactory() {

		CreateEntityManagerFactory cemf = new CreateEntityManagerFactory();
		factory = cemf.createEntityManagerFactory();

		return factory;
	}
	@Override
	public EntityManager creatEntityManager() {
		manager = factory.createEntityManager();

		return manager;
	}

	public List<User> validateUser(User user) throws Exception {
		daoResource = new DaoResource();
		List<User> u = daoResource.select("from User where username = :username and password = :pass",
				"username", user.getUsername(), "pass", ConverterSenha.convertStringToSHA(user.getPassword()+user.getUsername()), this);

		if(u.isEmpty() || u.size() == 0 || u.size() < 1){
			return null;
		}else{
			return u;
		}
	}
	
	public void createUser(User user) throws Exception {
		daoResource = new DaoResource();

		System.out.println("Convertendo...");
		System.out.println(user.getPassword());
		
		user.setPassword(ConverterSenha.convertStringToSHA(user.getPassword()+user.getUsername()));
		
		System.out.println("Salvando...");
		daoResource.save(user, this);
	}
	
	public List<Autorizacao> findAutorizacao() throws Exception {
		daoResource = new DaoResource();

		List<Autorizacao> aut = daoResource.select("from Autorizacao", this);
		return aut;
	}
	
	public void adicionaPermissao(User user, List<Autorizacao> autorizacoes) throws Exception {
		daoResource = new DaoResource();
		
		User u = (User)daoResource.buscarPorId(User.class, user.getCdUser(), this);

		u.getAutorizacoes().addAll(autorizacoes);

		daoResource.save(u, this);
	}
}


